require('./search.css');
import {
    getGoodList
} from './ajax';


$(function () {

    $.init();
    let loading = false;
    if ($('.infinite-scroll-preloader').length <= 0) {
        $('.content').append(renderLoading());
        $.attachInfiniteScroll($('.infinite-scroll'));
    }
    loading = true;
    $('.infinite-scroll-preloader').show();
    getGoodList(keyword, cid, 0, (res) => {
        loading = false;
        $('.infinite-scroll-preloader').hide();
        $("#goods-page").data('page', 1);
        $('#goods-page .list-container').html(renderListItem(res.data));
    });


    $(document).on('infinite', '.infinite-scroll-bottom', function () {
        // 如果正在加载，则退出
        if (loading) return;
        // 设置flag
        loading = true;
        $('.infinite-scroll-preloader').show();
        let page = $("#goods-page").data('page');
        getGoodList(keyword, cid, page, (res) => {
            if (res.rel == 1) {
                loading = false;
                $('.infinite-scroll-preloader').hide();
                $("#goods-page").data('page', page + 1);
                $('#goods-page .list-container').append(renderListItem(res.data));
            } else {
                $.detachInfiniteScroll($('.infinite-scroll'));
                // 删除加载提示符
                $('.infinite-scroll-preloader').remove();
                $.toast(res.msg);
                return;
            }
        });
    });
})

const renderListItem = (data) => {

    let markup = $.map(data, function (val) {
        let item = `
          <li>
                <a href="${goodsDetail}?gid=${val.gid}" class="item-link item-content" data-transition='slide-in'>
                    <div class="item-media"><img
                            src="/upload/${val.goods_thumb}"
                            width="80"></div>
                    <div class="item-inner">                  
                        <div class="item-subtitle">${val.goods_name}</div>
                        <div class="item-subtitle">￥${val.true_price}</div>
                        <div class="item-subtitle">库存${val.goods_num}件</div>                       
                    </div>
                </a>
            </li>
    `;

        return item;

    });


    return markup.join('');
};

const renderLoading = () => {
    return `
    <div class="infinite-scroll-preloader">
        <div class="preloader"></div>
    </div>
    `;
}